<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace XiaoZhuBundle\Helper;

use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use XiaoZhuBundle\Helper\Pagination;

class MyController extends Controller {

    public function getBasicInfo()
    {
        $info = array();
        $site = array('title'=>'小主商城', 'description'=>'网站的描述', 'keywords'=>'网站关键词', 'phone'=>'12345678');
        $good_num = 3;
        $good = array('cart_img'=>'bundles/xiaozhu/temp/cart-img.jpg', 'num'=>3, 'name'=>'商品名称', 'price'=>1000);
        $userInfo = $this->getSessionUserInfo();
        $tmp = array('username'=>$userInfo["username"], 'logout'=>$userInfo["logout"], 'count'=>$good_num, 'money'=>$good['num']*$good['price']*$good_num, 'cartimg'=>'bundles/xiaozhu/temp/cart-img.jpg',
            'good'=>$good);
        $info['site'] = $site;
        $info['tmp'] = $tmp;

        ////////////////////////////////////////////////////////////
        //分类信息
        $cat_cat1_attr1 = array('银镶钻','铂金镶钻','钯金镶钻','珍珠','施华洛世奇元素','天然宝石','人造水晶','人工宝石','K金镶钻');
        $cat_cat1_attr2 = array('貔貅','观音','花草','生肖','动物','关公','佛','人物');
        $cat_cat1_attr3 = array('100~150','150~200','200~250','250~300','300~350','350以上');
        $cat_cat1_bands = array('bundles/xiaozhu//temp/brands/next.jpg','bundles/xiaozhu//temp/brands/next.jpg','bundles/xiaozhu//temp/brands/next.jpg','bundles/xiaozhu//temp/brands/next.jpg','bundles/xiaozhu//temp/brands/next.jpg');
        $cat['cat1']=array('attr1'=>$cat_cat1_attr1, 'attr2'=>$cat_cat1_attr2, 'attr3'=>$cat_cat1_attr3, 'bands'=>$cat_cat1_bands);

        $cat_cat2_attr1 = array('婚庆','生肖','圆形/水滴','花草','心形','字母','卡通','扁圆');
        $cat_cat2_attr2 = array('耳钉','耳环','耳线','耳夹','其它');
        $cat['cat2']=array('attr1'=>$cat_cat2_attr1, 'attr2'=>$cat_cat2_attr2);

        $cat_cat3_attr1 = array('黑色','白色','红色','紫色','绿色','橙色','驼色','花色','灰色','粉色','玫瑰红');
        $cat_cat3_attr2 = array('发箍/发圈','横夹','边夹','抓夹','发绳','插梳','发饰套装','发梳','竖夹/香蕉夹','皇冠','八字夹','盘发棒','顶夹','簪子');
        $cat['cat3']=array('attr1'=>$cat_cat3_attr1,'attr2'=>$cat_cat3_attr2);

        $cat_cat4_attr1=array('情人节','生日','纪念日','新年礼物','七夕节');
        $cat_cat4_attr2 = array('升学礼','升迁礼','聚会礼','送行礼');
        $cat['cat4'] = array('attr1'=>$cat_cat4_attr1, 'attr2'=>$cat_cat4_attr2);

        $cat_cat5_attr1=array('施华洛世奇','T400','千寻海风','JOLEE','旭平首饰','简丹');
        $cat_cat5_attr2=array('陈欣','依泰连娜','烟雨江南','special','萌趣趣','瑞诺');
        $cat_cat5_attr3=array('美丽公主','银千惠','倾爱','凤凰涅槃','城市玉光','AGATHA');
        $cat['cat5'] = array('attr1'=>$cat_cat5_attr1, 'attr2'=>$cat_cat5_attr2, 'attr3'=>$cat_cat5_attr3);

        $info['cat']=$cat;
        //////////////////////////////////////////////////////////////////////////////

        $slider = array('layer1'=>'bundles/xiaozhu/temp/sliders/slide1/bg.jpg','layer2'=>'bundles/xiaozhu/temp/sliders/slide2/bg.jpg',
            'layer3'=>'bundles/xiaozhu/temp/sliders/slide3/bg.jpg','layer4'=>'bundles/xiaozhu/temp/sliders/slide4/bg.jpg');
        $info['slider']=$slider;


        $new_product=array('product1'=>array('no'=>1,'name'=>'产品名称1', 'price'=>102, 'img_src'=>'bundles/xiaozhu/temp/products/model1.jpg'),
            'product2'=>array('no'=>2,'name'=>'产品名称2', 'price'=>112, 'img_src'=>'bundles/xiaozhu/temp/products/model2.jpg'),
            'product3'=>array('no'=>3,'name'=>'产品名称3', 'price'=>122, 'img_src'=>'bundles/xiaozhu/temp/products/model6.jpg'),
            'product4'=>array('no'=>4,'name'=>'产品名称4', 'price'=>132, 'img_src'=>'bundles/xiaozhu/temp/products/model4.jpg'),
            'product5'=>array('no'=>5,'name'=>'产品名称5', 'price'=>142, 'img_src'=>'bundles/xiaozhu/temp/products/model5.jpg'),
            'product6'=>array('no'=>6,'name'=>'产品名称6', 'price'=>152, 'img_src'=>'bundles/xiaozhu/temp/products/model3.jpg'),
            'product7'=>array('no'=>7,'name'=>'产品名称7', 'price'=>162, 'img_src'=>'bundles/xiaozhu/temp/products/model7.jpg'));

        $info['products']=$new_product;

        $home_cat = array('cat2'=>'bundles/xiaozhu/temp/cat/item2.png',
            'cat3'=>'bundles/xiaozhu/temp/cat/item3.png',
            'cat4'=>'bundles/xiaozhu/temp/cat/item4.png',
            'cat5'=>'bundles/xiaozhu/temp/cat/item5.png',
            'cat6'=>'bundles/xiaozhu/temp/cat/item6.png');
        $info['home_cat'] = $home_cat;
        return $info;
    }

    public function getSessionUserInfo()
    {
        $info =  $this->get("session")->get("userInfo");
        if (!isset($info["logout"])) {
            $info = array(
                "username"  => "游客",
                "logout"    => TRUE,
            );
            $this->setSessionUserInfo($info);

        }
        return $info;
    }

    public function setSessionUserInfo($data = array())
    {
        if (is_array($data) && !empty($data)) {
            $this->get("session")->set( "userInfo" , $data );
//            foreach ($data as $key => $val)  {
//                $this->get("session")->set( $key , $val );
//            }
        }
    }

    /**
     * json 格式输出结果
     * @param $result
     * @param $info
     * @param $data
     * @return Response
     */
    public function json_out ($result,$info = "",$data = "")
    {
        $request = Request::createFromGlobals();
        if (!$debug = $this->getParamRequired("debug",$request)) {$debug = 0;}
        //todo 上线后请将调试功能去掉。

        if (!is_array($data)) {
            $data = (array)$data;
        }
        $this->formatArrayValues2String($data);
        if ($debug) {
            $re = array(
                "result"=> $result ? "$result" : "0",
                "data"  => $data   ? $data  : "",
                "error"  => $info  ? $info : "",
            );
            return new Response(json_encode($re),200,array("content-type"=>"application/json"));
        } else {
            $re = array(
                "result"=> $result ? "$result" : "0",
                "data"  => $data   ? json_encode( $data ) : json_encode( "" ),
                "error"  => $info  ? $info : "",
            );
            return new Response(json_encode($re),200);
        }

    }

    private function formatArrayValues2String(&$data)
    {
        foreach ($data as &$d) {
            if (!is_array($d)) {
                $d .= "";
            } else {
                $this->formatArrayValues2String($d);
            }
        }
    }

    /**
     * js弹窗提示结果后跳转
     * @param $path
     * @param $msg
     * @param $success
     * @return Response
     */
    public function js_out($msg,$path = -1, $success = 0)
    {
        $info = $this->getBasicInfo();
        if (is_numeric($path)) {
            $path = "javascript:history.go($path);";
        }
        $data = array(
            "url"   => $path,
            "msg"   => $msg,
            "success"=> $success,
        );
        $data = array_merge($info,$data);
        return $this->render("XiaoZhuBundle::message.html.twig",$data);
    }

    /**
     * 获取必填参数
     * @param $paramName
     * @return bool|mixed
     */
    public function getParamRequired($paramName)
    {
        $request = Request::createFromGlobals();
        if ($request->request->has("$paramName")) {
            return $request->get("$paramName");
        }
        if ($request->query->has("$paramName")) {
            return $request->get("$paramName");
        }
        return false;
    }

    /**
     * @param $base_url
     * @param $total_rows
     * @param int $per_page
     * @return array
     */
    public function creatPage($first_url,$base_url,$total_rows,$per_page = 10)
    {
        $config['first_url'] = $first_url;
        $config['base_url'] = $base_url;
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
        $config['reuse_query_string'] = TRUE;

        //分页基础配置
        $config['num_links'] = 3;
        $config['first_link'] = '首页';
        $config['prev_link'] = '«上一页';
        $config['full_tag_open'] = '<div class ="btn-group" >';
        $config['full_tag_close'] = '</div>';
        $config['cur_tag_open'] = '<a class ="btn red" >';
        $config['cur_tag_close'] = '</a>';
        $config['next_link'] = '下一页»';
        $config['last_link'] = '末页';

        $pageBuilder = new Pagination($config);
        $page =  $pageBuilder->create_links();
        return array(
            "total"     => $total_rows,
            "perPage"   => $per_page,
            "page"      => $page
        );
    }


    public function createMyForm($entityName , $entity , $actionUrl = "" , $method = "POST")
    {
        $config = array(
            "entity"   => $entity,
            "actionUrl"   => $actionUrl,

        );
        $options = array(
            "attr"  => array(
                "action" => $actionUrl,
                "method" => $method,
            ),
        );

        $form = $this->createFormBuilder($config["entity"],$options)->getForm();
        $m = $this->getDoctrine()->getManager();
        $formRows = new MyForms($m);
        foreach ($formRows->$entityName() as $key => $param) {
            $form->add($key,$this->type2RealType($param["showType"]),$this->basicParam($param["showType"],$param["label"],$param["dataType"],$param["option"]));
        }
        return $form;
    }

    private function type2RealType($type)
    {
        switch ($type) {
            case "article":
                $realType = "textarea";
                break;
            case "select":
                $realType = "choice";
                break;
            case "radio":
                $realType = "choice";
                break;
            case "checkbox":
                $realType = "choice";
                break;
            case "pic":
                $realType = "search";
                break;
            case "pics":
                $realType = "search";
                break;
            case "datetime":
            case "time":
            case "date":
                $realType = "text";
                break;
            default:
                $realType = $type;

        }
        return $realType;
    }

    public function basicParam($type,$name,$dataType,$option)
    {
        $attr = isset($option["attr"])?$option["attr"]:array();
        $attr = array_merge($attr,array("datatype"=>$dataType));
        $otherParam = isset($option["other"])?array_merge(array("label"=>$name),$option["other"]):array("label"=>$name);
        switch ($type) {
            case "select"://选择
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-single-select",
                    ),$attr),
                    "expanded"=>"0",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "radio"://单选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-multi-radio",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "checkbox"://多选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-multi-checkbox",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"1",
                ),$otherParam);
                return $basic;
                break;
            case "article"://富文本
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "editor",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            case "date"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd'})" ,
                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            case "time"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'HH:mm:ss'})" ,
                        'datatype'=>"/^(\d{1,2}:){2}\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            case "datetime"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"input rule-date-input" ,
                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" ,
                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}\s{1}(\d{1,2}:){2}\d{1,2}$/" ,
                        'errormsg'=>"请选择正确的日期",
                    ),$attr)
                ),$otherParam);
                return $basic;
                break;
            default:
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        //nothing
                    ),$attr),
                ),$otherParam);
                return $basic;
        }
    }

    public function DB($bundleName)
    {
        $em = $this->getDoctrine()->getManager();
        $rep = $em->getRepository($bundleName);
        return $rep;
    }

    public function EM()
    {
        $em = $this->getDoctrine()->getManager();
        return $em;
    }

    public function chkExist($bundleName ,$condition = array())
    {
        $rep = $this->DB($bundleName);
        $entity = $rep->findBy($condition);
        if ($entity) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

}
